package config

import (
	"errors"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
	"sync"
)

const (
	defaultConfigPath = "./config"
)

var configInstance *Config
var configOnce sync.Once

// GetConfig 缓存加载
func GetConfig() *Config {
	configOnce.Do(func() {
		var err error
		configInstance, err = Load()
		if err != nil {
			panic(err)
		}
	})
	return configInstance
}

func Load() (*Config, error) {
	v := viper.New()
	// 动态设置 配置名称
	env := os.Getenv("APP_ENV")
	if env == "" {
		env = "dev"
	}
	// 显式指定配置文件名
	v.SetConfigName(env)
	v.AddConfigPath(defaultConfigPath)
	v.SetConfigType("yaml")
	v.AutomaticEnv()
	v.SetEnvPrefix("APP")

	if err := v.ReadInConfig(); err != nil {
		return nil, errors.New("load config file failed: " + err.Error())
	}

	var cfg Config
	if err := v.Unmarshal(&cfg); err != nil {
		return nil, errors.New("unmarshal config file failed: " + err.Error())
	}
	reloadConfig(v)
	return &cfg, nil
}

func reloadConfig(v *viper.Viper) {
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Printf("Config file changed: %s\n", e.Name)
	})
}
